<template>
  <el-form :model="form" label-width="100px">
    <el-form-item label="手机号" required>
      <el-input 
        v-model="form.phone"
        placeholder="请输入手机号"
        clearable
      ></el-input>
    </el-form-item>

    <el-form-item label="密码" required>
      <el-input
        v-model="form.password"
        type="password"
        show-password
        placeholder="6-20位字母数字组合"
      ></el-input>
    </el-form-item>

    <el-form-item label="真实姓名" required>
      <el-input
        v-model="form.fullName"
        placeholder="请输入真实姓名"
      ></el-input>
    </el-form-item>

    <el-form-item v-if="userType === 1" label="邀请码" required>
      <el-input
        v-model="form.inviteCode"
        placeholder="请输入管理员邀请码"
      ></el-input>
    </el-form-item>

    <el-button 
      type="primary" 
      class="auth-btn"
      @click="handleRegister"
    >{{ userType === 1 ? '管理员注册' : '立即注册' }}</el-button>
  </el-form>
</template>

<script setup>
import { ref } from 'vue'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'

const props = defineProps({
  userType: {
    type: Number,
    default: 0
  }
})

const form = ref({
  phone: '',
  password: '',
  fullName: '',
  inviteCode: ''
})

const handleRegister = async () => {
  try {
    const formData = new FormData();
    formData.append('phone', form.value.phone);
    formData.append('password', form.value.password);
    formData.append('fullName', form.value.fullName);

    let endpoint = '/user/register';
    if (props.userType === 1) {
      endpoint = '/user/admin/register';
      formData.append('adminToken', form.value.inviteCode);
    }

    const { data } = await axios.post(endpoint, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (data.includes('成功')) {
      ElMessage.success('注册成功，请登录');
      location.href = '/login';
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.error || '注册失败');
  }
}
</script>

<style scoped>
.auth-btn {
  width: 100%;
  margin-top: 20px;
  height: 40px;
}
</style>